import React, { useState } from 'react';
import { useDispatch } from 'react-redux';
import { useSelector } from 'react-redux';
import {
  addTodoActionCreator,
  delTodoActionCreator,
  updateTodoActionCreator,
} from './store/action/todo';
import './styles/base.css';
import './styles/index.css';

export default class App extends React.Component {
  render() {
    return (
      <section className="todoapp">
        <Header></Header>
        <Main></Main>
        <Footer></Footer>
      </section>
    );
  }
}

function Main() {
  // 4. 取出state，需要按模块名去取出
  const { list } = useSelector((state) => state.todo);

  const dispatch = useDispatch();
  return (
    <section className="main">
      <input id="toggle-all" className="toggle-all" type="checkbox" />
      <label htmlFor="toggle-all">全选</label>
      <ul className="todo-list">
        {list.map((item) => {
          return (
            <li className={item.isDone ? 'completed' : ''} key={item.id}>
              <div className="view">
                <input
                  className="toggle"
                  type="checkbox"
                  checked={item.isDone}
                  onChange={() => dispatch(updateTodoActionCreator(item.id))}
                />
                <label>{item.task}</label>
                <button
                  className="destroy"
                  onClick={() => dispatch(delTodoActionCreator(item.id))}
                ></button>
              </div>
            </li>
          );
        })}
      </ul>
    </section>
  );
}
function Header() {
  const [task, setTask] = useState('');
  const dispatch = useDispatch();

  const handleKeyDown = (e) => {
    if (e.keyCode === 13) {
      dispatch(addTodoActionCreator(task));
    }
  };

  return (
    <header className="header">
      <h1>todos</h1>
      <input
        className="new-todo"
        placeholder="需要做什么"
        autoFocus
        onChange={(e) => setTask(e.target.value)}
        onKeyDown={handleKeyDown}
        value={task}
      />
    </header>
  );
}

function Footer() {
  return (
    <footer className="footer">
      <span className="todo-count">
        <strong>1</strong> 剩余
      </span>
      <ul className="filters">
        <li>
          <a className="all selected" href="#/">
            全部
          </a>
        </li>
        <li>
          <a className="active" href="#/active">
            未完成
          </a>
        </li>
        <li>
          <a className="completed" href="#/completed">
            已完成
          </a>
        </li>
      </ul>
      <button className="clear-completed">清除已完成</button>
    </footer>
  );
}
